package com.pansoft.kline.fragment;

import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.DefaultFillFormatter;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.Utils;
import com.google.gson.Gson;
import com.pansoft.kline.adapter.DealAnalyzeAppointOrderAdapter;
import com.pansoft.kline.adapter.DealAnalyzeEntryOrderAdapter;
import com.pansoft.kline.adapter.DealAnalyzeTurnoverOrderAdapter;
import com.pansoft.kline.base.KlineBaseFragment;
import com.pansoft.kline.formatter.ValueFormatter;
import com.pansoft.kline.greendao.DaoSessionUtil;
import com.pansoft.kline.model.ConfigCoinBean;
import com.pansoft.kline.model.ConfigMarketBean;
import com.pansoft.kline.model.ConfigSiteBean;
import com.pansoft.kline.model.DealRealAnalyzeAppointOrderModel;
import com.pansoft.kline.model.DealRealAnalyzeDepthModel;
import com.pansoft.kline.model.DealRealAnalyzeEntryOrderModel;
import com.pansoft.kline.model.DealRealAnayzeTurnoverOrderModel;
import com.pansoft.kline.model.TableInfo;
import com.pansoft.kline.util.KLineUtil;
import com.pansoft.kline.util.MarketNumberUtils;
import com.pansoft.kline.widget.MyMarkerView;
import com.pansoft.openplanet.R;
import com.utilcode.util.ConvertUtils;
import com.utilcode.util.TimeUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import static com.pansoft.openplanet.constant.MarketConstant.MARKET_DETAIL_ANYLYZE_APPOINT_ORDER_URL;
import static com.pansoft.openplanet.constant.MarketConstant.MARKET_DETAIL_ANYLYZE_DEPTH_URL;
import static com.pansoft.openplanet.constant.MarketConstant.MARKET_DETAIL_ANYLYZE_ENTRY_ORDER_URL;
import static com.pansoft.openplanet.constant.MarketConstant.MARKET_DETAIL_ANYLYZE_TURNOVER_ORDER_URL;

/**
 * @author : zzj
 * @e-mail : zhangzhijun@pansoft.com
 * @date : 2018/11/10 13:51
 * @desc : 分析fragment
 * @version: 1.0
 */
public class DealRealAnalyzeFragment extends KlineBaseFragment implements OnChartValueSelectedListener, View.OnClickListener {

    /**
     * 箭头的大小
     */
    private static final int ARROW_SIZE = ConvertUtils.dp2px(10);

    LineChart lineChart;

    /**
     * 买  卖  最新价 低  高  对应的数据
     */
    private LineDataSet dataSetBuy, dataSetSale, dataSetNewsPrice, dataSetLow, dataSetHigh;

    private boolean isBuy = true, isSale = true, isNewPrice = true, isLow = true, isHigh = true;

    /**
     * 挂单列表
     */

    RecyclerView rv_entry_order;
    /**
     * 委单量列表
     */

    RecyclerView rv_appoint;

    /**
     * 成交量列表
     */

    RecyclerView rv_turnover;

    private LinearLayout ll_buy;
    private LinearLayout ll_sale;
    private LinearLayout ll_news_price;
    private LinearLayout ll_low;
    private LinearLayout ll_high;
    /**
     *     委单量数据切换点击事件
     */
    private LinearLayout ll_appoint;
    /**
     * 成交量item
     */
    private LinearLayout ll_turnover_order;
    //挂单进度
    private ProgressBar pb_entry_order;
    //买单10档
    private TextView tv_progress_buy;
    //卖盘10档
    private TextView tv_progress_sell;

    private TextView tv_appoint_right;
    private TextView tv_appoint_left;
    //成交量文本
    private TextView tv_turnover_num;

    /**
     * 挂单列表适配器
     */
    private DealAnalyzeEntryOrderAdapter entryOrderAdapter;
    /**
     * 委托量列表适配器
     */
    private DealAnalyzeAppointOrderAdapter appointOrderAdapter;
    /**
     * 成交量列表适配器
     */
    private DealAnalyzeTurnoverOrderAdapter turnoverOrderAdapter;

    List<TableInfo> entryOrderList = new ArrayList<>();
    List<TableInfo> appointOrderList = new ArrayList<>();
    List<TableInfo> turnoverOrderList = new ArrayList<>();
    /**
     *  原始委单量数据
     */
    List<TableInfo> defaultAppointOrderList = new ArrayList<>();
    /**
     * 原始成交量数据
     */
    List<TableInfo> defaultTurnoverOrderList = new ArrayList<>();

    private String marketId;
    private ConfigCoinBean coinBean;
    private ConfigMarketBean marketBean;
    private ConfigSiteBean siteBean;
    /**
     * 判断委单量和
     */
    private int clickAppointOrder = 1,clickTurnoverOrder = 1;
    public static DealRealAnalyzeFragment newInstance(String marketId) {
        Bundle args = new Bundle();
        DealRealAnalyzeFragment fragment = new DealRealAnalyzeFragment();
        //当前coin的site，coin的name
        args.putString("marketId", marketId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initArgs(Bundle bundle) {
        super.initArgs(bundle);
        marketId = bundle.getString("marketId");
        marketBean = DaoSessionUtil.getInstance().getConfigMarketBeanDao().load(marketId);
        coinBean = DaoSessionUtil.getInstance().getConfigCoinBeanDao().load(marketBean.getCoin());
        siteBean = DaoSessionUtil.getInstance().getConfigSiteBeanDao().load(marketBean.getSite());
    }

    @Override
    public void refreshPage() {

    }

    @Override
    public void requestData() {
        initData();
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_deal_real_analyze;
    }


    @Override
    protected void initWidget(View root) {

        lineChart = root.findViewById(R.id.lineChart);
        rv_entry_order = root.findViewById(R.id.rv_entry_order);
        rv_appoint = root.findViewById(R.id.rv_appoint);
        rv_turnover = root.findViewById(R.id.rv_turnover);
        rv_entry_order = root.findViewById(R.id.rv_entry_order);
        ll_buy = root.findViewById(R.id.ll_buy);
        ll_sale = root.findViewById(R.id.ll_sale);
        ll_news_price = root.findViewById(R.id.ll_news_price);
        ll_low = root.findViewById(R.id.ll_low);
        ll_high = root.findViewById(R.id.ll_high);
        ll_appoint = root.findViewById(R.id.ll_appoint);
        ll_turnover_order = root.findViewById(R.id.ll_turnover_order);
        pb_entry_order = root.findViewById(R.id.pb_entry_order);
        tv_progress_buy = root.findViewById(R.id.tv_progress_buy);
        tv_progress_sell = root.findViewById(R.id.tv_progress_sell);
        tv_appoint_right = root.findViewById(R.id.tv_appoint_right);
        tv_appoint_left = root.findViewById(R.id.tv_appoint_left);
        tv_turnover_num = root.findViewById(R.id.tv_turnover_num);

        Drawable drawable = _mActivity.getResources().getDrawable(R.drawable.ic_chart_udarrow);
        drawable.setBounds( 0, 0, ARROW_SIZE,ARROW_SIZE);
        tv_appoint_left.setCompoundDrawables(null,null,drawable,null);
        tv_appoint_right.setCompoundDrawables(null,null,drawable,null);
        tv_turnover_num.setCompoundDrawables(null,null,drawable,null);
//        ll_buy.setOnClickListener(this);
//        ll_sale.setOnClickListener(this);
//        ll_news_price.setOnClickListener(this);
//        ll_low.setOnClickListener(this);
//        ll_high.setOnClickListener(this);
        ll_buy.setSelected(true);
        ll_sale.setSelected(true);
        ll_news_price.setSelected(true);
        ll_low.setSelected(true);
        ll_high.setSelected(true);

        ll_appoint.setOnClickListener(this);
        ll_turnover_order.setOnClickListener(this);
        initLineChart();
        //挂单量列表
        rv_entry_order.setLayoutManager(new LinearLayoutManager(getActivity()));
        entryOrderAdapter = new DealAnalyzeEntryOrderAdapter(R.layout.item_deal_analyze_entry_order, entryOrderList);
        rv_entry_order.setAdapter(entryOrderAdapter);
        //委单量列表
        rv_appoint.setLayoutManager(new LinearLayoutManager(getActivity()));
        appointOrderAdapter = new DealAnalyzeAppointOrderAdapter(R.layout.item_deal_analyze_appoint_order, appointOrderList);
        rv_appoint.setAdapter(appointOrderAdapter);
        //成交量列表
        rv_turnover.setLayoutManager(new LinearLayoutManager(getActivity()));
        turnoverOrderAdapter = new DealAnalyzeTurnoverOrderAdapter(R.layout.item_deal_analyze_turnover_order, turnoverOrderList);
        rv_turnover.setAdapter(turnoverOrderAdapter);

        rv_entry_order.setNestedScrollingEnabled(false);
        rv_appoint.setNestedScrollingEnabled(false);
        rv_turnover.setNestedScrollingEnabled(false);



        super.initWidget(root);
    }

    Random random = new Random();

    @Override
    protected void initData() {
        super.initData();
        requestAnalyzeDepth();
        requestEntryOrder();
        //请求委单量数据
        requestAppointOrder();
        //请求成交量
        requestTurnoverOrder();
    }

    /**
     * 请求委单量的数据
     * https://x.szsing.com:443/chart/m_orders?market_index=958
     */
    private void requestAppointOrder() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("market_index", marketId);
        JFCommonRequestManager.getInstance(getActivity()).requestGetByAsyn(TAG, MARKET_DETAIL_ANYLYZE_APPOINT_ORDER_URL, hashMap, new JFCommonRequestManager.ReqCallBack<String>() {
            @Override
            public void onReqSuccess(String result) {
                try {
                    DealRealAnalyzeAppointOrderModel appointOrderModel = new Gson().fromJson(result, DealRealAnalyzeAppointOrderModel.class);
                    if (appointOrderModel.getCode() != 0) {
//                        ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);
                        return;
                    }
                    disposeAnalyzeAppointOrderData(appointOrderModel);
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);

                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail_abnormal);
            }
        });
    }

    /**
     * 处理委单量的数据
     *
     * @param appointOrderModel
     */
    private void disposeAnalyzeAppointOrderData(DealRealAnalyzeAppointOrderModel appointOrderModel) {

        List<DealRealAnalyzeAppointOrderModel.DataBean.BidsBean> bidsBeans = appointOrderModel.getData().getBids();
        List<DealRealAnalyzeAppointOrderModel.DataBean.AsksBean> asksBeans = appointOrderModel.getData().getAsks();
        if (bidsBeans != null && bidsBeans.size() > 0) {
            appointOrderList.clear();
            defaultAppointOrderList.clear();
            for (int i = 0; i < bidsBeans.size(); i++) {
                double buy = getFormatCurrencyNumber(Double.valueOf(bidsBeans.get(i).getOriginalPrice()));
                double sell = getFormatCurrencyNumber(Double.valueOf(asksBeans.get(i).getOriginalPrice()));
                TableInfo tableInfo = new TableInfo();
                tableInfo.setFlowInto(asksBeans.get(i).getVolume());
                tableInfo.setTime(bidsBeans.get(i).getVolume());
                tableInfo.setBuy(buy + "");
                tableInfo.setSale(sell + "");
                tableInfo.setBarMax((float) (appointOrderModel.getData().getBaseProportion() * 100));
                tableInfo.setBarMin(-((float) (appointOrderModel.getData().getBaseProportion() * 100)));
                //左边是负的  右边是正的
                tableInfo.setBarLeft(-((float) (double) Double.valueOf(bidsBeans.get(i).getVolume())));
                tableInfo.setBarRight((float) (double) Double.valueOf(asksBeans.get(i).getVolume()));
                appointOrderList.add(tableInfo);
                defaultAppointOrderList.add(tableInfo);
            }
            appointOrderAdapter.notifyDataSetChanged();
        }else {
            View noDataView = LayoutInflater.from(_mActivity).inflate(R.layout.layout_chart_no_data,null);
            appointOrderAdapter.setEmptyView(noDataView);
        }


    }

    /**
     * 请求成交量的数据
     * https://x.szsing.com:443/chart/m_trades?market_index=958&timezone=0
     */
    private void requestTurnoverOrder() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("market_index", marketId);
        hashMap.put("timezone", "0");
        JFCommonRequestManager.getInstance(getActivity()).requestGetByAsyn(TAG, MARKET_DETAIL_ANYLYZE_TURNOVER_ORDER_URL, hashMap, new JFCommonRequestManager.ReqCallBack<String>() {
            @Override
            public void onReqSuccess(String result) {
                try {
                    DealRealAnayzeTurnoverOrderModel dealRealAnayzeTurnoverOrderModel = new Gson().fromJson(result, DealRealAnayzeTurnoverOrderModel.class);
                    if (dealRealAnayzeTurnoverOrderModel.getCode() != 0) {
//                        ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);
                        return;
                    }
                    disposeAnalyzeTurnoverOrderData(dealRealAnayzeTurnoverOrderModel);
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);

                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
//                ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail_abnormal);
            }
        });
    }

    /**
     * 处理成交量数据
     *
     * @param dealRealAnayzeTurnoverOrderModel
     */
    private void disposeAnalyzeTurnoverOrderData(DealRealAnayzeTurnoverOrderModel dealRealAnayzeTurnoverOrderModel) {
        List<DealRealAnayzeTurnoverOrderModel.DataBean.TradesBean> tradesBeans = dealRealAnayzeTurnoverOrderModel.getData().getTrades();
        if (tradesBeans != null && tradesBeans.size() > 0) {
            turnoverOrderList.clear();
            defaultTurnoverOrderList.clear();
            for (int i = 0; i < tradesBeans.size(); i++) {
                DealRealAnayzeTurnoverOrderModel.DataBean.TradesBean tradesBean = tradesBeans.get(i);
                double price = getFormatCurrencyNumber(tradesBean.getOriginalPrice());
                TableInfo tableInfo = new TableInfo();
                tableInfo.setFlowInto(tradesBean.getVolume());
                tableInfo.setTime(TimeUtils.millis2String(tradesBean.getTime(),new SimpleDateFormat("HH:mm:ss")));
                tableInfo.setBuy(price+"");
                tableInfo.setSale(tradesBean.getVolume());
                tableInfo.setBarMax(tradesBean.getType());
                tableInfo.setBarMin(0f);
//                tableInfo.setBarLeft(random.nextInt(100) * -1);
                tableInfo.setBarRight(Float.valueOf(tradesBean.getVolume()));
                turnoverOrderList.add(tableInfo);
                defaultTurnoverOrderList.add(tableInfo);
            }
            turnoverOrderAdapter.notifyDataSetChanged();
        }else {
            View noDataView = LayoutInflater.from(_mActivity).inflate(R.layout.layout_chart_no_data,null);
            turnoverOrderAdapter.setEmptyView(noDataView);
        }

    }

    /**
     * 请求挂单数据
     */
    private void requestEntryOrder() {
        //https://x.szsing.com:443/chart/m_order_books?market_index=958
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("market_index", marketId);
        JFCommonRequestManager.getInstance(getActivity()).requestGetByAsyn(TAG, MARKET_DETAIL_ANYLYZE_ENTRY_ORDER_URL, hashMap, new JFCommonRequestManager.ReqCallBack<String>() {
            @Override
            public void onReqSuccess(String result) {
                try {
                    DealRealAnalyzeEntryOrderModel analyzeEntryOrderModel = new Gson().fromJson(result, DealRealAnalyzeEntryOrderModel.class);
                    if (analyzeEntryOrderModel.getCode() != 0) {
//                        ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);
                        return;
                    }
                    disposeAnalyzeEntryOrderData(analyzeEntryOrderModel);
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);

                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail_abnormal);
            }
        });
    }

    /**
     * 处理挂单量数据
     *
     * @param analyzeEntryOrderModel
     */
    private void disposeAnalyzeEntryOrderData(DealRealAnalyzeEntryOrderModel analyzeEntryOrderModel) {
        pb_entry_order.setMax((int) (analyzeEntryOrderModel.getData().getAsksProportion() + analyzeEntryOrderModel.getData().getBidsProportion()));
        pb_entry_order.setProgress((int) analyzeEntryOrderModel.getData().getBidsProportion());
        tv_progress_buy.setText(KLineUtil.conversion(analyzeEntryOrderModel.getData().getBidsProportion() + "", "1", "0.000") + "%");
        tv_progress_sell.setText(KLineUtil.conversion(analyzeEntryOrderModel.getData().getAsksProportion() + "", "1", "0.000") + "%");
//        double cap = MarketNumberUtils.getRealPrice(siteBean.getUniqueKey(), marketBean.getCurrency(), wantCurrency, ((double)buyDepth.get(0).get(0)));
        List<DealRealAnalyzeEntryOrderModel.DataBean.BidsBean> bidsBeans = analyzeEntryOrderModel.getData().getBids();
        List<DealRealAnalyzeEntryOrderModel.DataBean.AsksBean> asksBeans = analyzeEntryOrderModel.getData().getAsks();

        if (bidsBeans != null && bidsBeans.size() > 0) {
            entryOrderList.clear();
            for (int i = 0; i < bidsBeans.size(); i++) {
                double time = getFormatCurrencyNumber( (bidsBeans.get(i).getOriginalPrice()));
                double sale = getFormatCurrencyNumber(((asksBeans.get(i).getOriginalPrice())));
                TableInfo tableInfo = new TableInfo();
                tableInfo.setFlowInto(asksBeans.get(i).getVolume());
                tableInfo.setTime(time + "");
                tableInfo.setBuy(bidsBeans.get(i).getVolume());
                tableInfo.setSale(sale + "");
                tableInfo.setBarMax(100f);
                tableInfo.setBarMin(-100f);
                tableInfo.setBarLeft(random.nextInt(100) * -1);
                tableInfo.setBarRight(random.nextInt(100));
                entryOrderList.add(tableInfo);
            }
            entryOrderAdapter.notifyDataSetChanged();
        }else {
            pb_entry_order.setMax(100);
            pb_entry_order.setProgress(50);
            View noDataView = LayoutInflater.from(_mActivity).inflate(R.layout.layout_chart_no_data,null);
            entryOrderAdapter.setEmptyView(noDataView);
        }

    }


    /**
     * 请求市场深度图的数据
     */
    private void requestAnalyzeDepth() {
        //https://x.szsing.com:443/v2/quote/depth/m_depth?marketID=958
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("marketID", marketId);
        JFCommonRequestManager.getInstance(getActivity()).requestGetByAsyn(TAG, MARKET_DETAIL_ANYLYZE_DEPTH_URL, hashMap, new JFCommonRequestManager.ReqCallBack<String>() {
            @Override
            public void onReqSuccess(String result) {
                try {
                    DealRealAnalyzeDepthModel dealRealAnalyzeDepthModel = new Gson().fromJson(result, DealRealAnalyzeDepthModel.class);
                    if (dealRealAnalyzeDepthModel.getCode() != 0) {
//                        ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);
                        return;
                    }
                    disposeAnalyzeDepthData(dealRealAnalyzeDepthModel);
                } catch (Exception e) {
                    e.printStackTrace();
//                    ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);
                    lineChart.setNoDataText(getResources().getString(R.string.kline_detail_no_data));
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail_abnormal);
            }
        });
    }

    /**
     * 处理市场深度图数据
     *
     * @param dealRealAnalyzeDepthModel
     */
    private void disposeAnalyzeDepthData(DealRealAnalyzeDepthModel dealRealAnalyzeDepthModel) {

        setDepthChartData(dealRealAnalyzeDepthModel);
    }


    private void initLineChart() {
        // disable description text
        lineChart.getDescription().setEnabled(false);
        // enable touch gestures
        lineChart.setTouchEnabled(true);
        // set listeners
        lineChart.setOnChartValueSelectedListener(this);
        lineChart.setDrawGridBackground(false);
        lineChart.setNoDataText(getResources().getString(R.string.kline_detail_no_data));
        lineChart.setNoDataTextColor(getResources().getColor(R.color.main_text_color));
        // create marker to display box when values are selected
        MyMarkerView mv = new MyMarkerView(_mActivity, R.layout.custom_marker_view);
        // Set the marker to the chart
        mv.setChartView(lineChart);
        lineChart.setMarker(mv);
        // enable scaling and dragging
        lineChart.setDragEnabled(false);
        lineChart.setScaleEnabled(false);
        lineChart.setPinchZoom(false);
        XAxis xAxis;
        {   // // X-Axis Style // //
            xAxis = lineChart.getXAxis();

            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
            xAxis.setDrawGridLines(false);
            xAxis.setAxisLineWidth(2);
            xAxis.setAxisLineColor(getResources().getColor(R.color.main_text_color));
            xAxis.setDrawLabels(true);
            xAxis.setTextColor(getResources().getColor(R.color.main_text_color));
            xAxis.setAvoidFirstLastClipping(true);
            xAxis.setLabelCount(5,true);
            xAxis.setValueFormatter(new ValueFormatter() {
                @Override
                public String getFormattedValue(float value) {
                    return ((int)value)+"";
                }
            });
        }

        YAxis yAxis;
        {   // // Y-Axis Style // //
            yAxis = lineChart.getAxisLeft();
            yAxis.setTextColor(getResources().getColor(R.color.main_text_color));
            // disable dual axis (only use LEFT axis)
            lineChart.getAxisRight().setEnabled(false);

            // horizontal grid lines
            yAxis.enableGridDashedLine(10f, 10f, 0f);
            yAxis.setDrawAxisLine(false);
            yAxis.setAxisMinimum(0);
            yAxis.setLabelCount(4);
        }
        lineChart.getLegend().setEnabled(false);

    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }

    /**
     * 设置市场深度图的数据
     *
     * @param depthChartData
     */
    private void setDepthChartData(DealRealAnalyzeDepthModel depthChartData) {
        List<List<Double>> buyDepth = depthChartData.getDepth().getBids();
        //设置买的图表样式
        if (buyDepth != null && buyDepth.size() > 0) {
            Collections.reverse(buyDepth);
            //设置最小值
            double capMin = getFormatCurrencyNumber(((double) buyDepth.get(0).get(0)));
            XAxis xAxis = lineChart.getXAxis();
            xAxis.setAxisMinimum((float) capMin);
            xAxis.setValueFormatter(new IAxisValueFormatter() {
                @Override
                public String getFormattedValue(float value, AxisBase axis) {
                    if (Float.isNaN(value) || Float.isInfinite(value)) {
                        return "";
                    }
                    if (value < 100) {
                        //保留两位小数
                        return String.format(Locale.getDefault(), "%.2f",
                                value);
                    }
                    return (int)value + "";
                }
            });
            dataSetBuy = new LineDataSet(disposeBuyDepthData(buyDepth, R.drawable.shape_bg_chart_depth_buy_green), "");
            dataSetBuy.setDrawIcons(false);
            // draw dashed line
            dataSetBuy.enableDashedLine(10f, 0, 0f);
            // black lines and points
            dataSetBuy.setColor(getResources().getColor(R.color.chart_deal_analyze_green));
            dataSetBuy.setCircleColor(Color.BLACK);
            // line thickness and point size
            dataSetBuy.setLineWidth(2f);
            dataSetBuy.setCircleRadius(3f);

            // draw points as solid circles
            dataSetBuy.setDrawCircleHole(false);

            dataSetBuy.setMode(LineDataSet.Mode.LINEAR);
            // customize legend entry
            dataSetBuy.setFormLineWidth(1f);
            dataSetBuy.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
            dataSetBuy.setFormSize(15.f);
            // text size of values
            dataSetBuy.setValueTextSize(9f);
            // draw selection line as dashed
            dataSetBuy.enableDashedHighlightLine(10, 10, 0);
            dataSetBuy.setDrawValues(false);
            // set the filled area
            dataSetBuy.setDrawFilled(true);
            dataSetBuy.setDrawCircles(false);
            dataSetBuy.setHighlightEnabled(true);
            dataSetBuy.setDrawHighlightIndicators(false);
//            dataSetBuy.setFillFormatter(new DefaultFillFormatter());
            if (Utils.getSDKInt() >= 18) {
                // drawables only supported on api level 18 and above
                Drawable drawable = ContextCompat.getDrawable(getActivity(), R.drawable.fade_blue);
                dataSetBuy.setFillDrawable(drawable);
            } else {
                dataSetBuy.setFillColor(Color.BLACK);
            }
        }else {
            return;
        }
        //设置卖的图表样式
        List<List<Double>> sellDepth = depthChartData.getDepth().getAsks();
        if (sellDepth != null && sellDepth.size() > 0) {
            //设置最大值
            double capMax = MarketNumberUtils.getRealPrice(siteBean.getUniqueKey(), marketBean.getCurrency(), wantCurrency, ((double) sellDepth.get(sellDepth.size()-1).get(0)));
            lineChart.getXAxis().setAxisMaximum((float) capMax);
            dataSetSale = new LineDataSet(disposeBuyDepthData(sellDepth, R.drawable.shape_bg_chart_depth_sale_red), "");

            dataSetSale.setDrawIcons(false);
            // draw dashed line
            dataSetSale.enableDashedLine(10, 0, 0);
            // black lines and points
            dataSetSale.setColor(getResources().getColor(R.color.chart_deal_analyze_red));
            // line thickness and point size
            dataSetSale.setLineWidth(2);

            // 设置图表上的值是否显示
            dataSetSale.setDrawValues(false);
            dataSetSale.setDrawCircleHole(false);
            dataSetSale.setMode(LineDataSet.Mode.LINEAR);
            // 绘制区域
            dataSetSale.setDrawFilled(true);
            //是否绘制圆点
            dataSetSale.setDrawCircles(false);
            //是否弹marker
            dataSetSale.setHighlightEnabled(false);
            //是否启用点指示器
            dataSetSale.setDrawHighlightIndicators(false);
            dataSetBuy.setFillFormatter(new DefaultFillFormatter());
            // set color of filled area
            if (Utils.getSDKInt() >= 18) {
                // drawables only supported on api level 18 and above
                Drawable drawable = ContextCompat.getDrawable(getActivity(), R.drawable.fade_red);
                dataSetSale.setFillDrawable(drawable);
            } else {
                dataSetSale.setFillColor(Color.BLACK);
            }
        }
        //添加到图表中
        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        dataSets.add(dataSetBuy);
        dataSets.add(dataSetSale);
        //设置最新价的数据
        List<Entry> values3 = new ArrayList<>();
        values3.add(new Entry((float) getFormatCurrencyNumber(depthChartData.getTicker().getLast()), 0, getResources().getDrawable(R.drawable.shape_bg_chart_depth_new_price_red)));
        dataSetNewsPrice = getDataSet(values3);
//        dataSets.add(dataSetNewsPrice);
        //设置低的数据
        List<Entry> values4 = new ArrayList<>();
        values4.add(new Entry((float) getFormatCurrencyNumber(depthChartData.getTicker().getLow()), 0, getResources().getDrawable(R.drawable.shape_bg_chart_depth_low_green)));
        dataSetLow = getDataSet(values4);
//        dataSets.add(dataSetLow);
        //设置高的数据
        List<Entry> values5 = new ArrayList<>();
        values5.add(new Entry((float) getFormatCurrencyNumber(depthChartData.getTicker().getHigh()), 0, getResources().getDrawable(R.drawable.shape_bg_chart_depth_high_light)));
        dataSetHigh = getDataSet(values5);
        dataSetHigh.setDrawIcons(true);
//        dataSets.add(dataSetHigh);

        // create a data object with the data sets
        LineData data = new LineData(dataSets);
        // set data
        lineChart.setData(data);
    }

    private LineDataSet getDataSet(List<Entry> values) {
        LineDataSet set2;
        // create a dataset and give it a type
        set2 = new LineDataSet(values, "");
        set2.setDrawIcons(true);
        // draw points as solid circles
        set2.setDrawCircleHole(false);
        // set the filled area
        set2.setDrawFilled(false);
        set2.setDrawCircles(false);
        set2.setHighlightEnabled(true);
        set2.setDrawValues(false);
        set2.setDrawHighlightIndicators(false);

        return set2;
    }

    /**
     * 处理市场深度图 买 的数据
     */
    private ArrayList<Entry> disposeBuyDepthData(List<List<Double>> buyDepth, int drawable) {
        ArrayList<Entry> values = new ArrayList<>();
        for (int i = 0; i < buyDepth.size(); i++) {
            List<Double> doubles = buyDepth.get(i);
            double x = getFormatCurrencyNumber(doubles.get(0));
            double y =  doubles.get(1);
            values.add(new Entry((float) x, (float) y, getResources().getDrawable(drawable)));
        }
        return values;

    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.ll_buy) {
            //买
            if (dataSetBuy != null) {
                if (isBuy) {
                    lineChart.getLineData().getDataSets().remove(dataSetBuy);
                    isBuy = false;
                } else {
                    lineChart.getLineData().getDataSets().add(dataSetBuy);
                    isBuy = true;
                }
                lineChart.invalidate();
                ll_buy.setSelected(isBuy);
            }

        } else if (view.getId() == R.id.ll_sale) {
            //卖
            if (dataSetSale != null) {
                if (isSale) {
                    lineChart.getLineData().getDataSets().remove(dataSetSale);
                    isSale = false;

                } else {
                    lineChart.getLineData().getDataSets().add(dataSetSale);
                    isSale = true;
                }
                lineChart.invalidate();
                lineChart.setPinchZoom(true);
                ll_sale.setSelected(isSale);
            }
        } else if (view.getId() == R.id.ll_news_price) {
            //最新价
            if (dataSetNewsPrice != null) {
                if (isNewPrice) {
                    lineChart.getLineData().getDataSets().remove(dataSetNewsPrice);
                    isNewPrice = false;
                } else {
                    lineChart.getLineData().getDataSets().add(dataSetNewsPrice);
                    isNewPrice = true;
                }
                lineChart.invalidate();
                ll_news_price.setSelected(isNewPrice);
            }
        } else if (view.getId() == R.id.ll_low) {
            //低
            if (dataSetLow != null) {
                if (isLow) {
                    lineChart.getLineData().getDataSets().remove(dataSetLow);
                    isLow = false;
                } else {
                    lineChart.getLineData().getDataSets().add(dataSetLow);
                    isLow = true;
                }
                lineChart.invalidate();
                ll_low.setSelected(isLow);
            }
        } else if (view.getId() == R.id.ll_high) {
            //高
            if (dataSetHigh != null) {
                if (isHigh) {
                    lineChart.getLineData().getDataSets().remove(dataSetHigh);
                    isHigh = false;
                } else {
                    lineChart.getLineData().getDataSets().add(dataSetHigh);
                    isHigh = true;
                }
                lineChart.invalidate();
                ll_high.setSelected(isHigh);
            }
        }else if(view.getId() == R.id.ll_appoint){
            //委单量量Top item点击事件
            switchAppointOrderData();

        }else if(view.getId() == R.id.ll_turnover_order){
            //成交量Top item点击事件
            switchTurnoverOrderData();
        }
    }



    /**
     * 切换成交量的数据
     */
    private void switchTurnoverOrderData() {

        if(clickTurnoverOrder == 1){
            clickTurnoverOrder = 2;
            Drawable drawable = _mActivity.getResources().getDrawable(R.drawable.ic_chart_up_arrow);
            drawable.setBounds( 0, 0, ARROW_SIZE,ARROW_SIZE);

            tv_turnover_num.setCompoundDrawables(null,null,drawable,null);
            //对集合进行排序；
            Collections.sort(turnoverOrderList, new Comparator<TableInfo>() {
                @Override
                public int compare(TableInfo o1, TableInfo o2) {
                    return ((int)(Double.valueOf(o1.getSale())*1000))-((int)(Double.valueOf(o2.getSale())*1000));
                }
            });
            turnoverOrderAdapter.notifyDataSetChanged();
        }else if(clickTurnoverOrder == 2){
            clickTurnoverOrder = 3;
            Drawable drawable = _mActivity.getResources().getDrawable(R.drawable.ic_chart_down_arrow);
            drawable.setBounds( 0, 0, ARROW_SIZE,ARROW_SIZE);
            tv_turnover_num.setCompoundDrawables(null,null,drawable,null);
            //对集合进行排序；
            Collections.sort(turnoverOrderList, new Comparator<TableInfo>() {
                @Override
                public int compare(TableInfo o1, TableInfo o2) {
                    return ((int)(Double.valueOf(o2.getSale())*1000))-((int)(Double.valueOf(o1.getSale())*1000));
                }
            });
            turnoverOrderAdapter.notifyDataSetChanged();
        }else if(clickTurnoverOrder == 3){
            clickTurnoverOrder = 1;
            Drawable drawable = _mActivity.getResources().getDrawable(R.drawable.ic_chart_udarrow);
            drawable.setBounds( 0, 0, ARROW_SIZE,ARROW_SIZE);
            tv_turnover_num.setCompoundDrawables(null,null,drawable,null);
            turnoverOrderList.clear();
            turnoverOrderList.addAll(defaultTurnoverOrderList);
            turnoverOrderAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 切换委单量数据数据
     * @param
     */
    private void switchAppointOrderData(){

        //委单量Top item点击事件
        if(clickAppointOrder == 1){
            clickAppointOrder = 2;
            Drawable drawable = _mActivity.getResources().getDrawable(R.drawable.ic_chart_up_arrow);
            drawable.setBounds( 0, 0, ARROW_SIZE,ARROW_SIZE);
            tv_appoint_left.setCompoundDrawables(null,null,drawable,null);
            tv_appoint_right.setCompoundDrawables(null,null,drawable,null);
            List<TableInfo> buyTables = new ArrayList<>();
            List<TableInfo> saleTables = new ArrayList<>();
            buyTables.addAll(appointOrderList);
            saleTables.addAll(appointOrderList);
            //对集合进行排序；
            Collections.sort(buyTables, new Comparator<TableInfo>() {
                @Override
                public int compare(TableInfo o1, TableInfo o2) {
                    return ((int)(Double.valueOf(o1.getTime())*1000))-((int)(Double.valueOf(o2.getTime())*1000));
                }
            });
            Collections.sort(saleTables, new Comparator<TableInfo>() {
                @Override
                public int compare(TableInfo o1, TableInfo o2) {
                    return ((int)(Double.valueOf(o1.getFlowInto())*1000))-((int)(Double.valueOf(o2.getFlowInto())*1000));
                }
            });
            appointOrderList.clear();
            for(int i =0;i<buyTables.size();i++){
                TableInfo tableInfo = new TableInfo();
                tableInfo.setFlowInto(saleTables.get(i).getFlowInto());
                tableInfo.setTime(buyTables.get(i).getTime());
                tableInfo.setBuy(buyTables.get(i).getBuy() + "");
                tableInfo.setSale(saleTables.get(i).getSale() + "");
                tableInfo.setBarMax(buyTables.get(i).getBarMax());
                tableInfo.setBarMin(buyTables.get(i).getBarMin());
                //左边是负的  右边是正的
                tableInfo.setBarLeft(buyTables.get(i).getBarLeft());
                tableInfo.setBarRight(saleTables.get(i).getBarRight());
                appointOrderList.add(tableInfo);
            }
            appointOrderAdapter.notifyDataSetChanged();
        }else if(clickAppointOrder == 2){
            clickAppointOrder = 3;
            Drawable drawable = _mActivity.getResources().getDrawable(R.drawable.ic_chart_down_arrow);
            drawable.setBounds( 0, 0, ARROW_SIZE,ARROW_SIZE);
            tv_appoint_left.setCompoundDrawables(null,null,drawable,null);
            tv_appoint_right.setCompoundDrawables(null,null,drawable,null);
            //对集合进行排序；
            Collections.sort(appointOrderList, new Comparator<TableInfo>() {
                @Override
                public int compare(TableInfo o1, TableInfo o2) {
                    return ((int)(Double.valueOf(o2.getTime())*1000))-((int)(Double.valueOf(o1.getTime())*1000));
                }
            });
            appointOrderAdapter.notifyDataSetChanged();
        }else if(clickAppointOrder == 3){
            clickAppointOrder = 1;
            Drawable drawable = _mActivity.getResources().getDrawable(R.drawable.ic_chart_udarrow);
            drawable.setBounds( 0, 0, ARROW_SIZE,ARROW_SIZE);
            tv_appoint_left.setCompoundDrawables(null,null,drawable,null);
            tv_appoint_right.setCompoundDrawables(null,null,drawable,null);
            appointOrderList.clear();
            appointOrderList.addAll(defaultAppointOrderList);
            appointOrderAdapter.notifyDataSetChanged();
        }
    }
    /**
     * 计算价格方法
     *
     * @param number
     * @return
     */
    public double getFormatCurrencyNumber(double number) {
        return MarketNumberUtils
                .getRealPrice(siteBean.getUniqueKey(), marketBean.getCurrency(), wantCurrency, number);
    }
}
